package cn.shujuhai.workflow.service.flow;

import cn.shujuhai.common.domain.SysUser;
import cn.shujuhai.common.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.IdentityService;
import org.flowable.idm.api.User;
import org.flowable.idm.api.UserQuery;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * +
 *
 * @Author: NiuYaHu
 * @Date: 2025/3/31 11:05
 * @Description:
 **/
@Service
@RequiredArgsConstructor
public class UserSyncService {

    final SysUserService sysUserService; // 业务系统用户Mapper
    final IdentityService identityService; // Flowable的用户服务

    /**
     * 同步用户数据到Flowable
     */
    public void syncUsers() {
        // 从业务系统获取所有用户
        List<SysUser> sysUsers = this.sysUserService.list();

        // 遍历业务系统用户
        for (SysUser sysUser : sysUsers) {
            // 检查Flowable中是否已存在该用户
            UserQuery userQuery = this.identityService.createUserQuery().userId(sysUser.getUsername());
            User user = userQuery.singleResult();
            if (user == null) {
                // 如果用户不存在，则创建新用户
                User newUser = identityService.newUser(sysUser.getUsername());
                newUser.setPassword(sysUser.getPassword());
                newUser.setEmail(sysUser.getEmail());
                newUser.setFirstName(sysUser.getName());
                newUser.setLastName(""); // 如果没有姓氏字段，可以留空
                identityService.saveUser(newUser);
                System.out.println("User created: " + sysUser.getUsername());
            } else {
                // 如果用户已存在，则更新用户信息
                user.setPassword(sysUser.getPassword());
                user.setEmail(sysUser.getEmail());
                user.setFirstName(sysUser.getName());
                identityService.saveUser(user);
                System.out.println("User updated: " + sysUser.getUsername());
            }
        }
    }
}
